package com.zk.shop.servlet.goods;

import com.zk.shop.entity.Goods;
import com.zk.shop.service.GoodsService;
import com.zk.shop.service.Impl.GoodsServicesImpl;
import com.zk.shop.util.JSONServlet;
import com.zk.shop.util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 当进入主页面时加载这个页面，获取所有商品列表
 *
 * @author 关轶阳
 */
@WebServlet("/getAllgoodsServlet")
public class GetAllgoodsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        GoodsService goodsServices = new GoodsServicesImpl();
        int currPage = Integer.parseInt(request.getParameter("currPage"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        int sortsId = Integer.parseInt(request.getParameter("sortsId"));
        String keyWords = request.getParameter("keyWords");
        int count = goodsServices.getGoodsCount();
        int totalPages = PageUtil.getTotalPage(count, pageSize);
        List<Goods> goodsList = null;
        Map<String, Object> map = new HashMap<>();
        map.put("start", (currPage - 1) * pageSize);
        map.put("pageSize", pageSize);
        if (sortsId == 0) {
            map.put("keyWords", keyWords);
            goodsList = goodsServices.getAllgoods(map);
        } else if (sortsId != 0) {
            map.put("sortsId", sortsId);
            map.put("keyWords", keyWords);
            goodsList = goodsServices.getAllgoodsById(map);

        }

        Map<String, Object> maps = new HashMap<>();
        maps.put("goodsList", goodsList);
        maps.put("currPage", currPage);
        maps.put("totalPages", totalPages);
        JSONServlet.getJson(request, response, maps);



    }
}
